package xml;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import xml.jxb.yr.ObjectFactory;
import xml.jxb.yr.Weatherdata;
import org.xml.sax.SAXException;

/**
 * <p>Java class for parsing weather data in SysUtvikling project
 * @author 490501
 * @version 1.0.0.a
 * @since 1.0.0.a
 */
public class ParserWeather {
    /**
     * Current version of XSD schema (september 2012) 
     */
    public static String SCHEMA_1_8 = "http://api.yr.no/weatherapi/locationforecast/1.8/schema";
    private JAXBContext js;
    private Unmarshaller unmarshaller;

    
    /**
     * <p>Create new instance of xml parser with default character encoding <b>UTF-8</b>
     * and default xml schema http://api.yr.no/weatherapi/locationforecast/1.8/schema
     * @throws JAXBException if any JAXBException occurs
     * @throws SAXException  if any SAXException occurs during validation of xml model
     * @throws MalformedURLException if URL for xml schema is malformed
     */
    public ParserWeather(String _pathToSchema) throws JAXBException, SAXException, MalformedURLException {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new URL(_pathToSchema));
        this.js = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
        this.unmarshaller = js.createUnmarshaller();
        this.unmarshaller.setSchema(schema);
    }
    

    /**
     * <p> Gets weather forecast for place given by lattitude and longitude
     * @param lat lattitude for any place where weather data will be retrieved
     * @param lng longitude for any place where weather data will be retrieved
     * @return <code>Weatherdata.class</code> with requested information
     * @throws MalformedURLException if URL is invalid
     * @throws JAXBException if any JACBException occurs
     */
    public Weatherdata getWeatherData(float lat,float lng) throws MalformedURLException, JAXBException, IOException, UnmarshalException {
        Weatherdata e =  (Weatherdata) unmarshaller.unmarshal(
                new URL("http://api.yr.no/weatherapi/locationforecast/1.8/?lat="+lat+";lon="+lng));
        return e;
    }
    
}
